//
//  HomeVC.m
//  PeanutEbuy
//
//  Created by 赵甜 on 2020/3/16.
//  Copyright © 2020 赵甜. All rights reserved.
//

#import "HomeVC.h"
#import "HomeCollectionViewCell.h"
#import "HomeCustomView.h"
#import "HMSegmentedControl.h"

#import "CityList.h"
#import "ProductListViewController.h"
#import "ShoppingCarViewController.h"
#import "CXSearchViewController.h"
#import "TCBabyDeailtyRootVC.h"
#import "ClassificationViewController.h"


@interface HomeVC ()<UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout,UISearchBarDelegate>{
    UICollectionViewFlowLayout *flowLayout;
}

@property (strong, nonatomic) UICollectionView *collectionView;
@property (strong, nonatomic) UIView *contentView;
@property (strong, nonatomic) HomeCustomView * homeCustomView;
@property (nonatomic,strong) HMSegmentedControl *segmentedControl;




@end

@implementation HomeVC




- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self addCustomNaV];
    
    [self createCollectionView];
    
    [self classificationView];
    
}


-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = NO; // 使右滑返回手势可用
    self.navigationController.navigationBar.hidden = YES; // 隐藏导航
}

-(void)viewWillDisappear:(BOOL)animated{
    self.navigationController.navigationBar.hidden = NO;
    self.hidesBottomBarWhenPushed = NO;
}




//自定义导航栏
-(void)addCustomNaV{
    _ztNavigationBar = [ZTnavigationBar instanceView];
    _ztNavigationBar.ztsearchBar.placeholder =@"搜索您想找的商品";

    WeakSelf;
    _ztNavigationBar.cityBtnBlcok = ^{
        CityList *CTL = [[CityList alloc]init];
           CTL.selectCity = ^(NSString *cityName){
               NSLog(@"选择的城市:%@", cityName);
               [weakSelf.ztNavigationBar.citybtn setTitle:cityName forState:UIControlStateNormal];
               [weakSelf.ztNavigationBar.citybtn setTitle:cityName forState:UIControlStateSelected];
            };
        weakSelf.hidesBottomBarWhenPushed = YES;
        [weakSelf.navigationController pushViewController:CTL animated:YES];

    };
    
    _ztNavigationBar.messageBtnBlcok = ^{
        [weakSelf showMessage:@"消息" yOffset:1];
    };
    
    _ztNavigationBar.carBtnBlcok = ^{
        ShoppingCarViewController * CTL =  [[ShoppingCarViewController alloc]init];
        weakSelf.hidesBottomBarWhenPushed = YES;
        [weakSelf.navigationController pushViewController:CTL animated:YES];
    };
    _ztNavigationBar.beginEditingBlcok = ^{
        CXSearchViewController *CTL = [[CXSearchViewController alloc] init];
        weakSelf.hidesBottomBarWhenPushed = YES;
        [weakSelf.navigationController pushViewController:CTL animated:YES];
    };
    _ztNavigationBar.ztsearchBar.delegate = self;
    
    if (!self.ztNavigationBar.hidden) {
        [self.view addSubview:self.ztNavigationBar];
        [_ztNavigationBar update];
    }
    
    //自定义视图
    _contentView = [[UIView alloc]init];
    [self.view addSubview:_contentView];
     [_contentView mas_makeConstraints:^(MASConstraintMaker *make) {
         make.left.right.bottom.equalTo(self.view);
         make.top.equalTo(self.ztNavigationBar.mas_bottom);
     }];
    _contentView.frame = CGRectMake(0, self.ztNavigationBar.height, self.view.width, self.view.height-_ztNavigationBar.height);
    _contentView.backgroundColor = [UIColor redColor];
}


- (void)createCollectionView
{
    if(_collectionView == nil){

        //布局初始化
        flowLayout =[[UICollectionViewFlowLayout alloc]init];
     

        _collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 0, _contentView.width, _contentView.height) collectionViewLayout:flowLayout];
        [self.contentView addSubview:_collectionView];
//        [self.contentView mas_makeConstraints:^(MASConstraintMaker *make) {
//            make.top.left.bottom.right.equalTo(self.contentView);
//        }];
        
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        _collectionView.backgroundColor =RGB(245, 245, 245);
        
        _collectionView.showsHorizontalScrollIndicator = NO;//滚动显示
        _collectionView.showsVerticalScrollIndicator = NO;
        
        //分区头及Cell
        [_collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"MyCollectionViewHeaderView"];
        [_collectionView registerNib:[UINib nibWithNibName:@"HomeCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"TWCollectionViewCell"];
        
    }
}

//自定义-分类视图
-(void)classificationView{
    _homeCustomView = [HomeCustomView instanceView];
    _homeCustomView.frame = CGRectMake(0, -631, _collectionView.width, 631);
    [_homeCustomView UpdataUi];
    
    //处理跳转
    WeakSelf;
    _homeCustomView.jumpToClassification = ^(int selectIndex) {
        if (selectIndex ==0) {
            ClassificationViewController * CTL =  [[ClassificationViewController alloc]init];
            [weakSelf.navigationController pushViewController:CTL animated:YES];
        }
    };
 
    [self.collectionView addSubview:_homeCustomView];
    //设置内边距及偏移量
    self.collectionView.contentInset = UIEdgeInsetsMake(631, 0, 0, 0);
    self.collectionView.contentOffset = CGPointMake(0, -631.f);
    
}


-(void)jump_To_Product_Detail{
    NSString *path = [[NSBundle mainBundle] pathForResource:@"productDetail" ofType:@"json"];
    NSString *productlistStr = [NSString stringWithContentsOfFile:path usedEncoding:nil error:nil];
    NSDictionary *productlistDic = [productlistStr mj_JSONObject];
//    TCGoodsModel *goodsModel = [TCGoodsModel mj_objectWithKeyValues:productlistDic[@"data"]];

    TCBabyDeailtyRootVC *detailRootVC = [TCBabyDeailtyRootVC new];
//    detailRootVC.goodsID = @"402";
//    detailRootVC.goodsModel = goodsModel;
    self.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:detailRootVC animated:YES];
}



- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar{
    CXSearchViewController *CTL = [[CXSearchViewController alloc] init];
     self.hidesBottomBarWhenPushed = YES;
     [self.navigationController pushViewController:CTL animated:YES];
    return NO;
}

#pragma mark- collectionView delegate

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return 20;
}

/**
 创建区头视图和区尾视图
 */
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
    if (kind == UICollectionElementKindSectionHeader){
        UICollectionReusableView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"MyCollectionViewHeaderView" forIndexPath:indexPath];
            headerView.backgroundColor = [UIColor yellowColor];
        [self initSegmentedControl];
        [headerView addSubview:self.segmentedControl];
        [self.segmentedControl mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(headerView);
            make.right.equalTo(headerView);
            make.top.equalTo(headerView);
            make.height.mas_equalTo(headerView);
        }];
//         UILabel *titleLabel = [[UILabel alloc]initWithFrame:headerView.bounds];
//         titleLabel.text = [NSString stringWithFormat:@"第%ld个分区的区头",indexPath.section];
//         [headerView addSubview:titleLabel];
        return headerView;
    }
    return nil;
}


- (void)initSegmentedControl {


    NSString *unarriveCountStr = [NSString stringWithFormat:@"%@",@"附近"];
    NSString *arriveCountStr = [NSString stringWithFormat:@"%@",@"热销"];
    NSString *invalidCountStr = [NSString stringWithFormat:@"%@",@"热搜"];
    NSString *allCountStr = [NSString stringWithFormat:@"%@",@"最新"];
    self.segmentedControl = [[HMSegmentedControl alloc] initWithSectionTitles:@[unarriveCountStr, arriveCountStr,invalidCountStr,allCountStr]];

    self.segmentedControl.autoresizingMask = UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleWidth;
    self.segmentedControl.selectionStyle = HMSegmentedControlSelectionStyleTextWidthStripe;
    self.segmentedControl.backgroundColor = [UIColor whiteColor];
    self.segmentedControl.selectionIndicatorHeight = 3.f;
    self.segmentedControl.selectionIndicatorEdgeInsets = UIEdgeInsetsMake(0, 0, -5, 0);
    self.segmentedControl.selectionIndicatorColor = [UIColor mainBlueColor];
    self.segmentedControl.selectionIndicatorLocation = HMSegmentedControlSelectionIndicatorLocationDown;
    [self.segmentedControl setTitleFormatter:^NSAttributedString *(HMSegmentedControl *segmentedControl, NSString *title, NSUInteger index, BOOL selected) {

        NSMutableAttributedString *attString = [[NSMutableAttributedString alloc] initWithString:title];
        [attString addAttribute:NSFontAttributeName value:[UIFont boldSystemFontOfSize:16] range:NSMakeRange(0, title.length)];
        [attString addAttribute:NSForegroundColorAttributeName value:[UIColor blackColor] range:NSMakeRange(0, title.length)];

        NSRange titleRange = NSMakeRange(0, 0);
        switch (index) {
            case 0:
                titleRange = [title rangeOfString:@"未到访"];
                break;
            case 1:
                titleRange = [title rangeOfString:@"已到访"];
                break;
            case 2:
                titleRange = [title rangeOfString:@"已失效"];
                break;
            case 3:
                titleRange = [title rangeOfString:@"全部"];
                break;
        }

        UIColor *selectedColor = selected ? [UIColor whiteColor]:RGB(161, 168, 179);
        [attString addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:14] range:titleRange];
        [attString addAttribute:NSForegroundColorAttributeName value:selectedColor range:titleRange];
        return attString;

    }];

    [self.segmentedControl setIndexChangeBlock:^(NSInteger index) {

    }];
//    [self.view addSubview:self.segmentedControl];
}



//cell
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identifier = @"TWCollectionViewCell";
    HomeCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath];
//    cell.label.text = [NSString stringWithFormat:@"顺序为：%d",indexPath.row];
    return cell;

}


#pragma mark 点击单元格
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    UICollectionViewCell *cell = [collectionView cellForItemAtIndexPath:indexPath];
//    [cell setBackgroundColor:[UIColor greenColor]];
    
      [self jump_To_Product_Detail];
//    ProductListViewController * CTL =  [[ProductListViewController alloc]init];
//    self.hidesBottomBarWhenPushed = YES;
//    [self.navigationController pushViewController:CTL animated:YES];
    
}

//间距
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
     return UIEdgeInsetsMake(10, 10, 10, 10);//分别为上、左、下、右
}

//大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    float width = (self.contentView.width-30)/2;
    return CGSizeMake(width, width*1.15);
}

/**
 区头大小
 */
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{
    return CGSizeMake(kScreenWidth, 65);
}


#pragma mark - scrollViewDidScroll
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    NSLog(@"scrollView.contentOffset.y:%f",scrollView.contentOffset.y);
    
    float offsetY = scrollView.contentOffset.y;
    if (offsetY>=0) {
        self.collectionView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0);
        if (@available(iOS 9.0, *)) {
                 flowLayout.sectionHeadersPinToVisibleBounds = YES;
             } else {
                 // Fallback on earlier versions
             }
    }else{
        self.collectionView.contentInset = UIEdgeInsetsMake(631, 0, 0, 0);
        flowLayout.sectionHeadersPinToVisibleBounds = NO;

    }
    
    NSLog(@"beginOffsetY:%f",offsetY);
}


@end
